package com.tongguan.paypos.base;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.TextView;


import com.tongguan.paypos.R;
import com.tongguan.paypos.common.RequestCallback;
import com.tongguan.paypos.view.CustomProgressDialog;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;

/**
 * Created by Joylive on 2016/12/13 .
 */

public class BaseFragment extends Fragment {
    private static final int TIMER_DELAYED = 10;
    protected View rootView;
    protected BaseActivity frmCtx;
    protected Map<String ,Object> params;
    protected Timer mTime;
    protected CustomProgressDialog mDialog ;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        frmCtx = (BaseActivity) getActivity();
        mDialog = new CustomProgressDialog(frmCtx,"加载中...");
    }

    /**
     * Activity 跳转
     *
     * @param activity
     */
    protected void jumpFrm2Act(Class<? extends BaseActivity> activity) {
        jumpFrm2Act(activity, false);
    }

    protected void jumpFrm2Act(Class<? extends BaseActivity> activity,  boolean isFinish) {
        jumpFrm2Act(activity, null,  isFinish);
    }

    protected void jumpFrm2Act(Class<? extends BaseActivity> activity, Bundle bundle, boolean isFinish) {

        Intent intent = new Intent(frmCtx, activity);
        if (bundle != null) {
            intent.putExtras(bundle);
//            L.d("Bundle", "jumpAct: "+ bundle.toString());//打印bundle
        }
        startActivity(intent);
        if (isFinish) {
            frmCtx.finish();
        }
    }

    protected  void setTimer(Handler handler, int what) {
        mTime = new Timer();
        mTime.schedule(new TimerTask() {
            int times = TIMER_DELAYED * 1000;
            @Override
            public void run() {
                handler.sendMessage(handler.obtainMessage(what, times));
                times -= 1000;
            }
        }, 1000, 1000);
    }
    protected void setTitle(String title){
        TextView textView = (TextView) frmCtx.findViewById(R.id.toolbar_title);
        textView.setText(title);
    }

    //不返回onFail
    public abstract class AbstractRequestCallback implements RequestCallback.HttpCallback {
        public abstract void onResponse(String response, int id);
        public void onError(Call call, Exception e, int id){

        }
    }

    public void onBack(){
        frmCtx.onBackPressed();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mTime!=null){
            mTime.cancel();
        }
        if (mDialog!=null){
            mDialog.dismiss();
            mDialog=null;
        }
    }
}
